# -*-coding: utf-8 -*-
"""
    @Theme   : Redis Client
    @Time    : 2024/6/18 16:15
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
import json
import hashlib

import redis
from flask import current_app


class RedisClient:
    def __init__(self, host, port, password):
        self.chat_room_nick_set = 'chat_room_nick_set'
        self.cookie_nick = 'cookie-{}'
        self.chat_list = 'chat_list'
        self.client = redis.Redis(host=host, port=port, password=password)

    def is_nick_already_exists(self, nick):
        is_flag = self.client.sadd(self.chat_room_nick_set, nick)
        if is_flag == 1:
            return False
        return True

    def set_token(self, nick, token):
        self.client.set(self.cookie_nick.format(nick), token,
                        ex=current_app.config['CHAT_COOKIE_EXPIRE_TIME'])

    def get_token(self, nick):
        token = self.client.get(self.cookie_nick.format(nick))
        return None if not token else token.decode()

    def get_chat_list(self):
        return [json.loads(chat) for chat in
                self.client.lrange(self.chat_list, -current_app.config['CHAT_MSG_LENGTH'], -1)]

    def push_chat_info(self, chat_info):
        self.client.rpush(self.chat_list, json.dumps(chat_info))
        self.client.ltrim(self.chat_list, -current_app.config['CHAT_MSG_LENGTH'], -1)

    @staticmethod
    def format_msg_key(nick, msg):
        return f'{nick}{hashlib.md5(msg.encode()).hexdigest()}'

    def get_msg_expire_time(self, nick, msg):
        expire_time = self.client.ttl(self.format_msg_key(nick, msg))
        return expire_time

    def set_msg_expire_time(self, nick, msg):
        self.client.set(self.format_msg_key(nick, msg), 1,
                        ex=current_app.config['CHAT_MSG_EXPIRE_TIME'])
